昨天學到讓物件變成一個實體的樣子,並學會了物體與物體的碰撞,接著要繼續學如何用程式碼去判斷物件。
想要讓程式去判斷物件有沒有碰撞到其他物件,可以用Unity的內建方法— OnCollisionEnter2D,這個方法跟Update方法一樣,都會一直被重複執行。
Void OnCollisionEnter2D(Collision2D other)  //other是指碰撞到的東西 
{ 
  Debug.Log("撞到"); //當Player碰撞到物件時會輸出"撞到"
} 


我新增了叫作Floor1的標籤及叫作Floor2的標籤。
接著再點取Floor1這個物件→選取它的標籤。
Floor2的標籤設定方式也同上。
最後可以看到Floor1&Floor2各有各自的tag。

如此可以去修改剛剛的程式碼讓程式可以判斷Player撞到哪個物件。
void OnCollisionEnter2D(Collision2D other)  //other是指碰撞到的東西 
{ 
    if(other.gameObject.tag == "Floor1") 
    {
        Debug.Log("撞到 Floor1"); 
    }	 
    
    else if(other.gameObject.tag == "Floor2") 
    { 
        Debug.Log("撞到 Floor2"); 
    } 
} 

可以看到下方Console欄有輸出方塊撞到了Floor1或2。

因為這個遊戲如果Player掉下去Game畫面外就算遊戲結束,所以目前有多增加一個叫Deathline的物件,但我們只是想要知道它有沒有掉下去超過這條死亡線而已,並沒有要它站在DeathLine上,所以可以在DeathLine的Box Collider 2D(Inspect那欄)勾選Is Trigger的選取框。
勾選後就可以看到Player掉下去了。
那還需要再加個可以讓程式判斷有經過物件的方法—OnTriggerEnter2D
void OnTriggerEnter2D(Collision2D other)   
{ 
if(other.gameObject.tag == "DeathLine") 
{ 
Debug.Log("你輸了!"); 
}	 
  } 

可以看到Player能經過DeathLine且不會停留在上面,Console欄也會輸出訊息。
目前做到這邊的程式碼長這樣↓
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
    [SerializeField] float speed = 5f;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.D)) {
            transform.Translate(speed*Time.deltaTime,0,0);
        }
        else if(Input.GetKey(KeyCode.A)) {
            transform.Translate(-speed*Time.deltaTime,0,0);
        }
    }
     void OnCollisionEnter2D(Collision2D other)  //other是指碰撞到的東西 
    { 
    if(other.gameObject.tag == "Floor1") 
    {
        Debug.Log("撞到Floor1"); 
    }	 
    else if(other.gameObject.tag == "Floor2") 
    { 
        Debug.Log("撞到Floor2"); 
    } 
    
    }
     void OnTriggerEnter2D(Collider2D other) {
        if(other.gameObject.tag == "DeathLine") 
    {
        Debug.Log("你輸了!"); 
    }
    }
 }
今天學到的是昨天的延伸,所需的功能可以很輕易地透過內建function來達成,而因為Unity的內建function很完善,讓我們只要輸入它指定的function就可以達到想要的效果,不需要自己另外想個演算法真方便~~
參考網址:https://www.youtube.com/watch?v=nPW6tKeapsM&ab_channel=GrandmaCan-%E6%88%91%E9%98%BF%E5%AC%A4%E9%83%BD%E6%9C%83